import { memo, useEffect, useState } from 'react';
import type { ChangeEvent, FC, ReactNode } from 'react';
import { useNavigate, useLocation, useSearchParams } from 'react-router-dom';
import { Input } from 'antd';
import { LIST_SEARCH_KEY } from '@/constant';

interface IProps {
  children?: ReactNode;
}

const { Search } = Input;

const QuestionSearch: FC<IProps> = () => {
  const [value, setValue] = useState('');

  const navigate = useNavigate();
  const { pathname } = useLocation();
  const [searchParams] = useSearchParams();
  useEffect(() => {
    setValue(searchParams.get(LIST_SEARCH_KEY) || '');
  }, [searchParams]);

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    setValue(e.target.value);
  };

  const handleSearch = (value: string) => {
    navigate({
      pathname,
      search: `${LIST_SEARCH_KEY}=${value}`,
    });
  };
  return (
    <div>
      <Search
        placeholder="输入关键字搜索"
        allowClear
        value={value}
        onChange={handleChange}
        onSearch={handleSearch}
        style={{ width: 200 }}
      />
    </div>
  );
};

export default memo(QuestionSearch);
